<template>
  <div class="continuous-limitup-board-ladder basic-bgColor">
    <div class="ladder-wrapper" v-for="(item, index) in list" :key="index">
      <div
        class="count-ladder"
        :class="{
          firscount: index === 0,
          lastcount: index === list.length - 1,
        }"
      >
        <div class="left-wrapepr">
          <div class="ladder-count basic-text">{{ item.height }}板</div>
          <div class="add-minus-icon" @click="handleSelfStock(item)">
            <img :src="addOrMinus(item.addicon)" />
          </div>
        </div>
      </div>
      <div class="stock-list" :class="{ firslist: index === 0, lastlist: index === list.length - 1 }">
        <div
          class="item-wrapper"
          v-for="(stock, index) in item.code_list"
          :key="index"
          :class="{
            firsthree: index === 2,
            laststock: index === item.code_list.length - 1,
          }"
          @click="jumpfenshi(stock.code, item.height, item.code_list, stock.market_id)"
        >
          <span class="basic-text">{{ stock.name }}</span>
        </div>
      </div>
    </div>
    <div class="nodata" v-if="!loadtag && (!list || list.length == 0)">
      <div class="nopic"></div>
      <div class="basic-text-head">
        <div v-html="noDataMessage" style="text-align: center"></div>
      </div>
    </div>
    <div v-if="loadtag" class="loading">
      <Loading type="spinner"></Loading>
    </div>
  </div>
</template>

<script>
import {
  isBlackMode,
  getSelfCodeList,
  getUserId,
  isIos,
  newFenshiJump,
  getContinuousUp,
  getServeTime,
} from '../../utils/index';

import Bus from '../../utils/eventBus';
import dayjs from 'dayjs';

// atom-ui 引入
import '@atom/atom-ui/lib/loading/style';
import { Loading, Toast } from '@atom/atom-ui';

const thsBrokerList = ['ths', 'thspro', 'ifind', 'hkus'];
const NO_MESSAGE = '暂无数据';

export default {
  name: 'ContinuousLimitupLadder',

  props: {
    // 调用组件的业务 id（可为业务定制化需求）
    id: {
      type: String,
      default: '',
    },

    filterConcatText: {
      type: String,
      default: 'HS,GEM2STAR',
    },

    nowDate: {
      type: String,
      default: dayjs().format('YYYYMMDD'),
    },
  },

  watch: {
    filterConcatText: {
      handler() {
        this.getContinusData();
      },
    },

    nowDate: {
      handler() {
        this.init();
      },
    },
  },

  components: {
    Loading,
    Toast,
  },

  data() {
    return {
      selfStockList: [],
      fakeArray: [],
      list: [],
      size: '0.16em',
      isBlack: isBlackMode(),
      selfCodelist: [],
      flag: false,
      sh: 100,
      userId: '0',
      maidian: 'free_ztjj.lbtt.',
      loadtag: true,
      nowFilter: 'HS,GEM2STAR',
      isAndroid: !isIos(),
      isClosed: false,
      timer2: null,
      timerId: null,
      isInThs: false,
      noDataMessage: NO_MESSAGE, // 无数据展示文本
    };
  },
  created() {
    this.judgeIsInThs();
    let params = {};
    if (window.changeRouteBus) {
      params = {
        filter: window.changeRouteBus.filter,
        date: window.changeRouteBus.date,
      };
      this.nowFilter = window.changeRouteBus.filter;
      this.nowDate = window.changeRouteBus.date;
    } else {
      params = {
        filter: this.nowFilter,
        date: this.nowDate,
      };
    }
    this.init(params);
    this.timer2 = setInterval(this.judgeClose, 1000 * 60);
    this.timerId = setInterval(this.init, 3000 * 10);
  },

  beforeDestroy() {
    clearInterval(this.timer2);
    clearInterval(this.timerId);
    this.timer2 = null;
    this.timerId = null;
  },

  methods: {
    // 是否是端内
    judgeIsInThs() {
      thsBrokerList.forEach(item => {
        if (item == window.F10Utils.getBroker()) {
          this.isInThs = true;
        }
      });
    },
    changeRouteFun(e) {
      if (e && e.path && e.path === '/linkBoardLadder') {
        this.nowFilter = e.filter ? e.filter : this.nowFilter;
        this.nowDate = e.date ? e.date : this.nowDate;
        const params = {
          filter: this.nowFilter,
          date: this.nowDate,
          // _: sercretNum
        };
        this.init(params);
      }
    },
    // 是否不在盘中
    async judgeClose() {
      const result = await getServeTime(this.id);
      if (result.data.stat == '交易中' || result.data.stat == '午间休市') {
        this.isClosed = false;
      } else {
        if (this.isInThs) {
          this.isClosed = true;
        }
        this.isClosed = false;
      }
    },
    // 获取连板天梯数据
    async getContinusData(params) {
      const newParams = {
        filter: this.filterConcatText,
        date: this.nowDate,
      };
      const tempList = await getContinuousUp(this.id, newParams);
      // 10003和后端协议 开盘前状态码10003， 显示对应文案
      if (tempList.status_code === 10003) {
        this.noDataMessage = tempList.status_msg.replace('\n', '</br>');
        this.list = [];
        return;
      } else {
        this.noDataMessage = NO_MESSAGE;
      }

      this.list = this.complementArray(tempList.data);
      this.loadtag = false;
    },

    async init(params) {
      this.loadtag = true;
      await this.judgeClose();

      if (!params) {
        params = {
          filter: this.nowFilter,
          date: this.nowDate,
        };
      }

      this.userId = getUserId();
      if (this.userId != null && this.userId != '0' && !this.flag && this.isInThs) {
        try {
          getSelfCodeList().then(
            async res => {
              this.selfStockList = res.selfCodeList;
              try {
                await this.getContinusData(params);
              } catch (error) {
                console.log(error);
              }
            },
            async error => {
              try {
                await this.getContinusData(params);
              } catch (error) {
                console.log(error);
              }
            }
          );
        } catch (error) {
          this.loadtag = false;
        } finally {
          this.loadtag = false;
        }
      } else {
        try {
          await this.getContinusData(params);
        } catch (error) {
          console.log(error);
        }
        this.loadtag = false;
      }
    },

    complementArray(list) {
      const temp = list.map(item => {
        item.addicon = false;
        item.visible = false;
        const len = item.code_list.length;
        if (this.userId != null && this.userId != '0' && this.isInThs) {
          item.visible = true;
          // 判断对应板块个股是否全为自选股
          if (this.selfStockList && this.selfStockList.length > 0) {
            const arrset = this.arrayToMap(this.selfStockList);
            for (let i = 0; i < len; i++) {
              if (arrset.has(item.code_list[i].code)) {
                continue;
              } else {
                item.addicon = true;
                break;
              }
            }
          }
        }
        // 补充空数据，保证连板天梯每行3格占满
        const comlen = Math.ceil(len / 3) * 3 - len;
        const newArray = [];
        const temp = { code: '', name: ' ' };
        for (let i = 0; i < comlen; i++) {
          item.code_list.push(temp);
        }
        return item;
      });
      return temp;
    },
    // 提取自选股数组中的股票代码
    arrayToMap(array) {
      const set = new Set();
      for (let i = 0; i < array.length; i++) {
        set.add(array[i].stockcode);
      }

      return set;
    },
    // 修改加自选按钮图表
    addOrMinus(inSelf) {
      if (inSelf) {
        return '//i.thsi.cn/staticS3/mobileweb-upload-static-server.img/m/atom/dd9082d0-410d-44f7-a1b0-bbea483ab8d3.png';
      } else {
        return '//i.thsi.cn/staticS3/mobileweb-upload-static-server.img/m/atom/39f70526-7d1c-420d-84a2-2cfbb2b16d5f.png';
      }
    },

    handleSelfStock(item) {
      this.flag = true;
      //一键自选
      if (item.addicon) {
        const addList = [];
        item.code_list.forEach(val => {
          addList.push({
            marketid: String(val.market_id),
            stockcode: val.code,
          });
        });
        window.callNativeHandler('selfCodeAction', { action: 'addStocks', selfCodeListAdd: addList }, data => {
          if (data.state == 1) {
            if (this.isAndroid) {
              this.selfCodeSuccess('已添加至“自选股”');
            }
            item.addicon = !item.addicon;
            this.addOrMinus(item.addicon);
          } else if (data.state == 2 && this.isAndroid) {
            this.selfCodeWarn('自选股数量已达上限');
          }
        });
        window.hxmClickStat(`${this.maidian}${item.height}.lianban.jiazixuan`, {
          url_ver: 'F10-1725',
        });
        // alert("add stock");
      } else {
        const delList = [];
        for (let i = 0; i < item.code_list.length; i++) {
          const obj = {
            marketid: item.code_list[i].market_id,
            stockcode: item.code_list[i].code,
          };
          delList.push(obj);
        }
        window.callNativeHandler('selfCodeAction', { action: 'delStocks', selfCodeListDel: delList }, data => {
          if (data.state == 10) {
            if (this.isAndroid) {
              this.selfCodeSuccess('已移出“自选股”');
            }
            item.addicon = !item.addicon;
            this.addOrMinus(item.addicon);
          }
        });
        window.hxmClickStat(`${this.maidian}${item.height}.lianban.shanzixuan`, {
          url_ver: 'F10-1725',
        });
        // alert("minus stock");
      }
      //修改+-号

      this.flag = false;
    },

    jumpfenshi(stockcode, height, plist, marketId) {
      if (stockcode) {
        const marketList = [];
        const codeList = [];
        const nameList = [];
        plist.forEach((item, index) => {
          if (item.code) {
            codeList.push(item.code);
            if (item.market_id) {
              marketList.push(item.market_id);
            } else {
              marketList.push('');
            }
            if (item.name) {
              nameList.push(item.name);
            } else {
              nameList.push('');
            }
          } else{
            codeList.push('');
          }
        });
        const params = {
          stockcode: stockcode,
          marketid: marketId,
          namelist: nameList,
          marketlist: marketList,
          codelist: codeList,
        };
        newFenshiJump(params);
        window.hxmClickStat(`${this.maidian}${height}.lianban.${stockcode}`, {
          url_ver: 'F10-1725',
          targid: `agu_${stockcode}`,
        });
      }
    },
    // 弹窗
    selfCodeSuccess(content) {
      Toast(content);
    },

    selfCodeError(content) {
      Toast(content);
    },

    selfCodeWarn(content) {
      Toast(content);
    },
  },

  mounted() {
    if (this.isInThs) {
      this.isClosed = true;
    } else {
      this.isClosed = false;
    }
    this.sh = document.documentElement.scrollHeight;
  },
};
</script>

<style lang="less">
.continuous-limitup-board-ladder {
  margin: 0 28px;
  padding-bottom: 28px;
  * {
    box-sizing: border-box;
  }
  .loading {
    display: flex;
    justify-content: center;
  }
  .nodata {
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 14px;
    .nopic {
      height: 122px;
      width: 120px;
      background-image: url('../../images/empty.png');
      background-size: 100%;
      background-repeat: no-repeat;
      background-position: bottom left;
    }
    .basic-text-head {
      margin-top: 16px;
    }
  }
  .board-checkbox {
    font-size: 14px;
    margin-bottom: 16px;
    .checkbox-group {
      display: flex;
      align-items: center;
      position: relative;
      .checkbox-title {
        display: inline-block;
        margin-left: 4px;
        margin-right: 16px;
      }
      .checkbox-popup {
        position: absolute;
        top: 0;
        right: 0;
        display: flex;
        align-items: center;
        .checkbox-popup-name {
          display: inline-block;
          margin-right: 5px;
        }
      }
    }
  }
  .checkbox-group {
    font-size: 14px;
    padding-top: 16px;
    margin-bottom: 16px;
    .checkbox-group {
      display: flex;
      align-items: center;
      position: relative;
      .checkbox-title {
        display: inline-block;
        margin-left: 4px;
        margin-right: 16px;
      }
      .checkbox-popup {
        position: absolute;
        top: 0;
        right: 0;
        display: flex;
        align-items: center;
        .checkbox-popup-name {
          display: inline-block;
          margin-right: 5px;
        }
      }
    }
  }
  .ladder-wrapper {
    display: flex;

    .count-ladder {
      width: 20.03%;
      display: flex;
      align-items: center;
      // flex: 1;
      border: 4px solid #ffffff;
      background: rgba(246, 246, 246, 0.6);
      justify-content: center;
      .left-wrapepr {
        border: 1px solid transparent;
        display: flex;
        align-items: center;
        justify-content: center;
        .ladder-count {
          font-size: 28px;
          color: rgba(0, 0, 0, 0.84);
          font-weight: 500;
          text-align: right;
        }
        .add-minus-icon {
          height: 28px;
          width: 32px;
          max-width: 32px;
          display: flex;
          margin-left: 8px;
          img {
            width: 32px !important;
            max-width: 28px !important;
          }
        }
      }
    }
    .firscount {
      border-top-left-radius: 12px;
    }
    .lastcount {
      border-bottom-left-radius: 12px;
    }
    .stock-list {
      display: flex;
      width: 79.97%;
      -webkit-flex-wrap: wrap;
      -webkit-box-lines: multiple;
      -moz-flex-wrap: wrap;
      flex-wrap: wrap;
      background: rgba(0, 0, 0, 0.02);

      .item-wrapper {
        display: flex;
        width: 33.3%;
        align-items: center;
        justify-content: center;
        font-size: 28px;
        color: rgba(0, 0, 0, 0.84);
        line-height: 20px;
        height: 80px;
        border: 4px solid #ffffff;
        text-align: center;
      }
    }
    .firslist {
      border-top-right-radius: 12px;
      .firsthree {
        border-top-right-radius: 12px;
      }
    }
    .lastlist {
      border-bottom-right-radius: 12px;
      .laststock {
        border-bottom-right-radius: 12px;
      }
    }
  }
}

.dark {
  .continuous-limitup-board-ladder {
    margin: 0 28px;
    padding-bottom: 28px;
    .nodata {
      .nopic {
        background-image: url('../../images/empty-dark.png');
      }
    }
    .ladder-wrapper {
      .count-ladder {
        border: 4px solid #1e1e1e;
        background: rgba(255, 255, 255, 0.02);
      }
      .stock-list {
        background: rgba(255, 255, 255, 0.02);
        .item-wrapper {
          border: 4px solid #1c1c1c;
          // border: 1px solid red;
        }
      }
    }
  }
}
</style>
